"""
字幕对齐服务
"""
import os
from typing import Optional
from loguru import logger

from storyforge.models import Episode
from storyforge.utils import get_project_dir, load_json, save_text


class SubtitleService:
    """字幕服务"""
    
    def __init__(self):
        """初始化服务"""
        from storyforge.config import get_config
        self.config = get_config()
    
    def align(
        self,
        project_name: str,
        episode_index: int,
        audio_file: str,
        output_file: Optional[str] = None
    ) -> str:
        """
        对齐字幕
        
        Args:
            project_name: 项目名称
            episode_index: 剧集序号
            audio_file: 音频文件路径
            output_file: 输出文件路径，None则自动生成
            
        Returns:
            字幕文件路径（SRT格式）
        """
        project_dir = get_project_dir(project_name, self.config.paths.projects)
        episode_file = project_dir / f"episode_{episode_index}.json"
        
        episode_data = load_json(str(episode_file))
        if not episode_data:
            raise FileNotFoundError(f"剧集文件不存在: {episode_file}")
        
        episode = Episode(**episode_data)
        
        # 提取对白文本
        dialogues = self._extract_dialogues(episode)
        
        if not dialogues:
            logger.warning(f"第{episode_index}集没有对白内容")
            return ""
        
        # 生成字幕（简化实现：按句均分时间）
        # 实际应该使用ASR或强制对齐工具
        if not output_file:
            outputs_dir = self.config.paths.outputs
            os.makedirs(outputs_dir, exist_ok=True)
            output_file = os.path.join(outputs_dir, f"ep{episode_index}.srt")
        
        # 估算音频时长（简化，实际应该读取音频文件）
        estimated_duration = len(dialogues) * 3  # 假设每句3秒
        
        srt_content = self._generate_srt(dialogues, estimated_duration)
        save_text(srt_content, output_file)
        
        logger.info(f"字幕已生成: {output_file}")
        return output_file
    
    def _extract_dialogues(self, episode: Episode) -> list:
        """
        从剧集中提取对白列表
        
        Args:
            episode: 剧集对象
            
        Returns:
            对白字符串列表
        """
        dialogues = []
        
        script_json = episode.scriptJSON
        scenes = script_json.get("scenes", [])
        
        for scene in scenes:
            if "dialogue" in scene:
                dialogues.append(scene["dialogue"])
        
        if not dialogues and episode.outline:
            # 如果没有对白，使用大纲分段
            sentences = episode.outline.split('。')
            dialogues = [s.strip() + '。' for s in sentences if s.strip()]
        
        return dialogues
    
    def _generate_srt(self, dialogues: list, total_duration: float) -> str:
        """
        生成SRT格式字幕文本
        
        Args:
            dialogues: 对白字符串列表
            total_duration: 总时长（秒）
            
        Returns:
            SRT格式的字幕文本
        """
        srt_lines = []
        duration_per_dialogue = total_duration / len(dialogues) if dialogues else 0
        
        for idx, dialogue in enumerate(dialogues):
            start_time = idx * duration_per_dialogue
            end_time = (idx + 1) * duration_per_dialogue
            
            srt_lines.append(f"{idx + 1}")
            srt_lines.append(f"{self._format_timestamp(start_time)} --> {self._format_timestamp(end_time)}")
            srt_lines.append(dialogue)
            srt_lines.append("")
        
        return "\n".join(srt_lines)
    
    def _format_timestamp(self, seconds: float) -> str:
        """
        格式化时间戳为SRT格式（HH:MM:SS,mmm）
        
        Args:
            seconds: 时间（秒）
            
        Returns:
            SRT格式的时间戳字符串，例如：00:00:30,500
        """
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        millis = int((seconds % 1) * 1000)
        return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"

